<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <meta name="viewport"
          content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"/>
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <title>客服聊天</title>
    <script>
        (function (window) {//检查浏览器类型和ie版本
            var theUA = window.navigator.userAgent.toLowerCase();
            var isIE = (theUA.match(/msie\s\d+/) && theUA.match(/msie\s\d+/)[0]) || (theUA.match(/trident\s?\d+/) && theUA.match(/trident\s?\d+/)[0]);
            if (isIE) {
                //如果是IE，判断IE版本
                alert('非常抱歉！IE内核浏览器无法正常浏览该网页，请使用其他浏览器访问');
//                var ieVersion = theUA.match(/msie\s\d+/)[0].match(/\d+/)[0] || theUA.match(/trident\s?\d+/)[0];
//                if (ieVersion < 10) {
//                    alert('您的浏览器IE内核过低，可能会影响网页正常使用，建议升级或使用其他浏览器。');
//                }
            }
        })(window);
    </script>
    <link type="text/css" rel="stylesheet" href="js/emoji/jquery.emojiarea.css">
    <link type="text/css" rel="stylesheet" href="css/style.css">
</head>
<body class="ub ub-ver">
<div id="header">
    <div class="center ub">
        <div class="navLeft Btn" onclick="window.history.go(-1);"></div>
        <h1 id="title" class="ub-f">
            赵龙<span class="in"></span>
        </h1>

        <div class="navRight"></div>
    </div>
</div>

<div id="chatContent" class="conScrollY ub-f">
    <div id="pullDown">
        <div class="loading-warp">
            <div class="box">
                <div>
                    <img src="img/loading.gif"/>
                    <span class="text">下拉获取更多记录</span>
                </div>
            </div>
        </div>
        <div class="chatTime"><span>10:52:34</span></div>

        <div class="chat chatLeft ub">
            <div class="chatImg"><img src="img/src/userPicture.jpg"></div>
            <div class="ub-f">
                <div class="speakTime">2017-5-10 17:23:04</div>
                <div class="chatTxt ub">
                    <div class="chatAngle"></div>
                    <span>请问，这只股怎么样？</span>
                </div>
            </div>
        </div>

        <div class="chat chatLeft ub">
            <div class="chatImg"><img src="img/src/userPicture.jpg"></div>
            <div class="ub-f">
                <div class="speakTime">2017-5-10 17:23:04</div>
                <div class="chatTxt ub">
                    <div class="chatAngle"></div>
                    <span><a href="http://www.baidu.com">www.baidu.com</a></span>
                </div>
            </div>
        </div>

        <div class="chat chatLeft ub">
            <div class="chatImg"><img src="img/src/userPicture.jpg"></div>
            <div class="ub-f">
                <div class="speakTime">2017-5-10 17:23:04</div>
                <div class="chatTxt ub">
                    <div class="chatAngle"></div>
                    <span><a href="http://down.3uww.com/Zip_32051/%E6%95%B0%E5%AD%97%E7%AC%94%E8%AE%B0.zip">下载文件</a></span>
                </div>
            </div>
        </div>

        <!--<div class="chat chatLeft ub">-->
        <!--<div class="chatImg"><img src="img/src/userPicture.jpg"></div>-->
        <!--<div class="ub-f">-->
        <!--<div class="speakTime">2017-5-10 17:23:04</div>-->
        <!--<div class="chatTxt ub">-->
        <!--<div class="chatAngle"></div>-->
        <!--<span><img class="image" src="http://pic17.nipic.com/20111026/3631203_111238646000_2.jpg"></span>-->
        <!--</div>-->
        <!--</div>-->
        <!--</div>-->

        <div class="chat chatRight ub">
            <div class="ub-f">
                <div class="speakTime">2017-5-10 17:23:04</div>
                <div class="chatTxt ub ub-pe">
                    <div class="chatAngle"></div>
                    <span>还不错</span>
                </div>
            </div>
            <div class="chatImg"><img src="img/src/serverPicture.jpg"></div>
        </div>

        <!--<div class="chat chatRight ub">-->
        <!--<div class="ub-f">-->
        <!--<div class="speakTime">2017-5-10 17:23:04</div>-->
        <!--<div class="chatTxt ub ub-pe">-->
        <!--<div class="chatAngle"></div>-->
        <!--<span><img class="image" src="https://www.baidu.com/img/bd_logo1.png"></span>-->
        <!--</div>-->
        <!--</div>-->
        <!--<div class="chatImg"><img src="img/src/serverPicture.jpg"></div>-->
        <!--</div>-->


    </div>
</div>

<div id="chatFooter">
    <form class="ub ub-ac chatFooter">
        <div class="ub-f inputArea">
            <textarea id="chatVal" class="emojis-wysiwyg"></textarea>
        </div>
        <div class="chatIcon emoSend"></div>
        <div id="textOrRich" class="chatIcon richSend"></div>
        <input id="previewImg" type="file" accept="image/*" onchange="uploadImg(this);" style="display: none;">
    </form>
</div>


<script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="js/p-pull-refresh.js"></script>
<script type="text/javascript" src="js/layer_mobile/layer.js"></script>
<script type="text/javascript" src="js/emoji/jquery.emojiarea.js"></script>
<script type="text/javascript" src="js/emoji/faces5/emojis.js"></script>
<script>
    var $chatVal = $('#chatVal'), $inputDiv, $container = $('#chatContent'), $tOr = $('#textOrRich');
    var myPullDown;
    $(document).ready(function () {

        //初始化下拉刷新组件
        var $status = $('.loading-warp .text');
        var $pullDown = $('#pullDown');
        myPullDown = $pullDown.pPullRefresh({
            $el: $pullDown,
            $loadingEl: $('.loading-warp'),
            callbacks: {
                pullInit: function () {
                    $status.text('下拉获取更多记录');
                },
                pullStart: function () {
                    $status.text('松开获取消息记录');
                },
                start: function () {
                    $status.text('正在获取消息记录');
                    //TODO；请求
                    setTimeout(function () {
                        getMoreHistory(function () {
                            //获取消息成功后
                            myPullDown.reset(false);//重置下拉状态
                        });//获取并加载历史记录
                    }, 1000)

                }
            }
        });

        $container.scroll(function () {
            //滚动监听，只在滚动条高度为0时，才启用下拉组件
            var afterScrollTop = $container.scrollTop();
            if (afterScrollTop == 0) {
                myPullDown.setDestroy(false);//启用下拉组件
            } else {
                myPullDown.setDestroy(true);//销毁下拉组件
            }
        });

        chatContentScrollToB();//聊天内容滑动到最底部

        $('.emojis-wysiwyg').emojiarea({wysiwyg: true});//初始化输入框，绑定表情
        $inputDiv = $('.emoji-wysiwyg-editor');

        $chatVal.on('change', function (event) {
            //当输入框内容改变，切换发送按钮
            var textValue = $chatVal.val();
            if (textValue) {
                if ($tOr.hasClass('richSend')) {
                    $tOr.removeClass('richSend').addClass('textSend');
                }
            } else {
                if ($tOr.hasClass('textSend')) {
                    $tOr.removeClass('textSend').addClass('richSend');
                }
            }
        });

        $(document).on('click', '.textSend', function () {
            //点击发送按钮
            sendMsg();
        });

        $(document).on('click', '.richSend', function () {
            //点击图片按钮
            $('#previewImg').click();
        });

    });

    function chatContentScrollToB() {
        //聊天内容滑动到最底部
        $container.scrollTop($container[0].scrollHeight);
    }

    function utf16toEntities(str) {
        //用于把用utf16编码的字符转换成实体字符，以供后台存储
        var patt=/[\ud800-\udbff][\udc00-\udfff]/g; // 检测utf16字符正则
        str = str.replace(patt, function(char){
            var H, L, code;
            if (char.length===2) {
                H = char.charCodeAt(0); // 取出高位
                L = char.charCodeAt(1); // 取出低位
                code = (H - 0xD800) * 0x400 + 0x10000 + L - 0xDC00; // 转换算法
                return "&#" + code + ";";
            } else {
                return char;
            }
        });
        return str;
    }


    function sendMsg() {
        //发送消息
        var str = $.trim($chatVal.val());
        str = utf16toEntities(str);
        if (str) {
            var messageObj = {
                //测试数据
                msg_id: '',
                head_pic: '',
                type: '',
                time: '',
                content: str
            };
            addMsg(messageObj);//向聊天区域添加消息
            clearInput();//清空输入区域
            $inputDiv.focus();
        } else {
            clearInput();//清空输入区域
            //提示
            layer.open({
                content: '请输入内容',
                skin: 'msg',
                time: 2 //2秒后自动关闭
            });
        }
    }

    function clearInput() {
        //清空输入区域，同时改变发送按钮
        $chatVal.val('');//清空输入框
        $inputDiv.html('');//清空输入框
        if ($tOr.hasClass('textSend')) {
            $tOr.removeClass('textSend').addClass('richSend');
        }
    }

    function addMsg(message) {
        //向聊天区域添加消息 todo：字段待完善
        var spanHtml = returnChatHtml(message);
        $container.append(spanHtml);
        chatContentScrollToB();//聊天内容滑动到最底部
    }

    function returnChatHtml(message) {
        //解析消息，转换成html
        var dir = message.dir ? message.dir : 'right';//消息方向
        var type = message.type ? message.type : 'text';//类型
        var msg_id = message.msg_id;//id
        var head_pic = '';
        if (message.head_pic) {
            head_pic = message.head_pic;//头像
        } else {
            head_pic = dir == 'left' ? 'img/src/userPicture.jpg' : 'img/src/serverPicture.jpg';//头像
        }
        var time = message.time;//时间
        var content = message.content;//内容
        var spanHtml = '';//定义消息html
        switch (type) {
            case 'text':
                content = strToHtmlEmoji(content);//转换表情
                if (dir == 'left') {
                    spanHtml = '<div class="chat chatLeft ub" data-msgid="' + msg_id + '">' +
                            '<div class="chatImg"><img src="' + head_pic + '"></div>' +
                            '<div class="ub-f">' +
                            '<div class="speakTime">' + time + '</div>' +
                            '<div class="chatTxt ub">' +
                            '<div class="chatAngle"></div>' +
                            '<span>' + content + '</span>' +
                            '</div>' +
                            '</div>' +
                            '</div>';
                } else {
                    spanHtml = '<div class="chat chatRight ub" data-msgid="' + msg_id + '">' +
                            '<div class="ub-f">' +
                            '<div class="speakTime">' + time + '</div>' +
                            '<div class="chatTxt ub ub-pe">' +
                            '<div class="chatAngle"></div>' +
                            '<span>' + content + '</span>' +
                            '</div>' +
                            '</div>' +
                            '<div class="chatImg"><img src="' + head_pic + '"></div>' +
                            '</div>';
                }
                break;
            case 'img':
                if (dir == 'left') {
                    spanHtml = '<div class="chat chatLeft ub" data-msgid="' + msg_id + '">' +
                            '<div class="chatImg"><img src="' + head_pic + '"></div>' +
                            '<div class="ub-f">' +
                            '<div class="speakTime">' + time + '</div>' +
                            '<div class="chatTxt ub">' +
                            '<div class="chatAngle"></div>' +
                            '<span><img class="image" src="' + content + '"></span>' +
                            '</div>' +
                            '</div>' +
                            '</div>';
                } else {
                    spanHtml = '<div class="chat chatRight ub" data-msgid="' + msg_id + '">' +
                            '<div class="ub-f">' +
                            '<div class="speakTime">' + time + '</div>' +
                            '<div class="chatTxt ub ub-pe">' +
                            '<div class="chatAngle"></div>' +
                            '<span><img class="image" src="' + content + '"></span>' +
                            '</div>' +
                            '</div>' +
                            '<div class="chatImg"><img src="' + head_pic + '"></div>' +
                            '</div>';
                }
                break;
        }
        return spanHtml;
    }

    function uploadImg(e) {
        var imgLayerLoading;//定义loading动画对象
        //图片上传
        if (e.files && e.files[0]) {
            var fileObj = e.files[0]; // 获取文件对象

            var localPath = e.value;
            var fileType = (e.value.substring(localPath.lastIndexOf("."), e.value.length)).toLowerCase();
            if ((fileType != '.jpg') && (fileType != '.gif') && (fileType != '.jpeg') && (fileType != '.png') && (fileType != '.bmp')) {
                //提示
                layer.open({
                    content: '图片格式错误，请重新选择',
                    skin: 'msg',
                    time: 2 //2秒后自动关闭
                });
                return;
            }
            imgLayerLoading = layer.open({type: 2, content: '正在发送...'});//开始loading动画


            //上传
            var formDataObj = new FormData(); // FormData对象
            formDataObj.append("file", fileObj); // 把文件对象加入FormData 对象
            //... todo ajax提交formDataObj


            //文件操作，预览本地图片 todo:上传图片
            var reader = new FileReader();
            reader.onload = function (evt) {
                layer.close(imgLayerLoading);//关闭loading动画
                var imgSrc = evt.target.result;
                var messageObj = {
                    //测试数据
                    msg_id: '',
                    head_pic: '',
                    type: 'img',
                    time: '',
                    content: imgSrc
                };
                addMsg(messageObj);//向页面添加图片
            };
            reader.readAsDataURL(e.files[0]);//读取图像文件
        }
    }

    function getMoreHistory(cb) {
        //获取更多历史消息记录
        var $e = $('.loading-warp');
        //todo:获取数据并解析
        setTimeout(function () {
            cb();//回调函数
            var historyMsgArr = [
                //测试数据
                {
                    msg_id: '',
                    head_pic: '',
                    type: '',
                    dir: '',
                    time: '2017-05-08 12:35',
                    content: '这是历史消息'
                },
                {
                    msg_id: '',
                    head_pic: '',
                    type: '',
                    dir: 'left',
                    time: '2017-05-08 12:25',
                    content: '这也是是历史消息'
                }
            ];
            var historyHtml = '';
            $.each(historyMsgArr, function (index, item) {
                historyHtml += returnChatHtml(item);
            });
            $e.after(historyHtml);//将历史消息写入页面

            //计算历史消息的高度
            var length = $(historyHtml).length, historyH = $($('.chat')[length - 1]).position().top;
            //定位滚动条
            $container.scrollTop(historyH);

        }, 1000)
    }

    function onMessageChat(msgObj) {
        //接收消息处理
        var locId = getLocHrefStr('id');
        var senderId = msgObj.id;
        if (senderId == locId) {
            //当前消息直接展示
            addMsg(msgObj.message);
        }else{
            //非当前消息
            //todo 推送或提醒
        }

    }

    /**
     * 获取当前页面地址的参数值
     * @param name 参数名
     * @returns {null}
     */
    function getLocHrefStr(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = decodeURI(window.location.search.substr(1)).match(reg);//对中文解码
        if (r != null) return unescape(r[2]);
        return null;
    }

    setInterval(function () {
        //打开页面每5秒，模拟接收到消息
        var msgObj = {
            //测试数据
            type: 'kefu',//类型：老师：teacher；客服：kefu
            id: '123',
            pic: 'img/src/userPicture.jpg',
            name: '特朗普',
            message: {
                msg_id: '',
                head_pic: '',
                type: '',
                dir: 'left',
                time: '2017-5-15',
                content: '你好啊，测试消息来了'
            }
        };
        onMessageChat(msgObj);
    }, 5000);
</script>

</body>
</html>